import org.apache.hadoop.hive.ql.exec.UDF;

public class ConvertIdCardNumber15to18 extends UDF {
    /**
     * 将15位身份证号转换成18位
     * @param sfzjhm 15位身份证号
     * @return 返回15转换完成后的18位，或者原值
     */
    public String evaluate(String sfzjhm) {
        if(sfzjhm==null || "".equals(sfzjhm)){
            return null;
        }
        String regularExpression = "^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}";
        if (sfzjhm.matches(regularExpression)) {
            String idNumber_17 = sfzjhm.substring(0, 6) + "19" + sfzjhm.substring(6);
            return idNumber_17 + getVerifyCode(idNumber_17);
        }
        // 不满足返回原值
        return sfzjhm;
    }
    private static String getVerifyCode(String idNumber_17) {
        String[] ValCodeArr = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
        String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2" };

        int power = 0;
        for (int i = 0; i < 17; i++) {
            power += Integer.parseInt(String.valueOf(idNumber_17.charAt(i))) * Integer.parseInt(Wi[i]);
        }
        return ValCodeArr[power % 11];
    }
}